/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    2013 year
 *    Author: Esipenko Aleksey (Alexorleon)
 *    E-Mail: alexorleon@gmail.com
 */
#include "global.h"
#include "tablemodel.h"
#include <QApplication>
#include <QDataStream>
#include <QFile>
#include <QFontMetrics>
#include <QStyleOptionComboBox>
#include <QDebug>

namespace {
const int MaxColumns = 3;
}

QDataStream &operator<<(QDataStream &out, const ZipcodeItem &item)
{
    out << item.id << item.date_time << item.status << item.qrpath
        << /*item.qrtext << */item.performer/*<< item.placement*/;
    return out;
}


QDataStream &operator>>(QDataStream &in, ZipcodeItem &item)
{
    in >> item.id >> item.date_time >> item.status >> item.qrpath
        >> /*item.qrtext >> */item.performer/* >> item.placement*/;
    return in;
}


Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags theFlags = QAbstractTableModel::flags(index);
    //if (index.isValid())
        //theFlags |= Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
    return theFlags;
}

QVariant TableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() ||
        index.row() < 0 || index.row() >= zipcodes.count() ||
        index.column() < 0 || index.column() >= MaxColumns)
        return QVariant();
    const ZipcodeItem &item = zipcodes.at(index.row());
    if (role == Qt::SizeHintRole) {
        QStyleOptionComboBox option;
        switch (index.column()) {
            case Date: option.currentText = item.date_time; break;
            case Status: option.currentText = item.status; break;
            case Performer: option.currentText = item.performer; break;
            //case Placement: option.currentText = item.placement; break;
            default: Q_ASSERT(false);
        }
        QFontMetrics fontMetrics(data(index, Qt::FontRole).value<QFont>());

        option.fontMetrics = fontMetrics;
        QSize size(fontMetrics.width(option.currentText),
                   fontMetrics.height());
        return qApp->style()->sizeFromContents(QStyle::CT_ComboBox, &option, size);
    }
    if (role == Qt::DisplayRole || role == Qt::EditRole) {
        switch (index.column()) {
            case Date: return item.date_time;
            case Status: return item.status;
            case Performer: return item.performer;
            //case Placement: return item.placement;
            default: Q_ASSERT(false);
        }
    }
    // возвращаем id QR-кода, для записи в history
    if(role == Qt::UserRole){
        return item.id;
    }
    // возвращаем путь файла QR-кода, для сохранения
    if(role == 33){
        return item.qrpath;
    }
    return QVariant();
}


QVariant TableModel::headerData(int section,
        Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();
    if (orientation == Qt::Horizontal) {
        switch (section) {
            case Date: return tr("Дата создания");
            case Status: return tr("Статус");
            case Performer: return tr("Исполнитель");
            //case Placement: return tr("Место размещения");
            default: Q_ASSERT(false);
        }
    }
    return section + 1;
}


int TableModel::rowCount(const QModelIndex &index) const
{
    return index.isValid() ? 0 : zipcodes.count();
}


int TableModel::columnCount(const QModelIndex &index) const
{
    return index.isValid() ? 0 : MaxColumns;
}


bool TableModel::setData(const QModelIndex &index,
                         const QVariant &value, int role)
{
    if (!index.isValid() || role != Qt::EditRole ||
        index.row() < 0 || index.row() >= zipcodes.count() ||
        index.column() < 0 || index.column() >= MaxColumns)
        return false;
    ZipcodeItem &item = zipcodes[index.row()];
    switch (index.column()) {
        case Date: item.date_time = value.toString(); break;
        case Status: item.status = value.toString(); break;
        case Performer: item.performer = value.toString(); break;
        //case Placement: item.placement = value.toString(); break;
        default: Q_ASSERT(false);
    }
    emit dataChanged(index, index);
    return true;
}


/*bool TableModel::insertRows(int row, int count, const QModelIndex&)
{
    beginInsertRows(QModelIndex(), row, row + count - 1);
    for (int i = 0; i < count; ++i)
        zipcodes.insert(row, ZipcodeItem());
    endInsertRows();
    return true;
}*/


bool TableModel::removeRows(int row, int count, const QModelIndex&)
{
    beginRemoveRows(QModelIndex(), row, row + count - 1);
    for (int i = 0; i < count; ++i)
        zipcodes.removeAt(row);

    endRemoveRows();
    return true;
}


//void TableModel::load(const QString &filename)
void TableModel::addData(const int &id_, const QStringList &list)
{
    if (!list.isEmpty())
        m_list = list;

    ZipcodeItem item(
                id_,
                list.at(0),
                list.at(1),
                list.at(2),
                list.at(3));

    zipcodes << item;
    //qSort(zipcodes);
    //reset();
}

void TableModel::resetModel(){

    /*for(int i = 0; i < zipcodes.size(); ++i) {
        qDebug()<<zipcodes.at(i).id;
        qDebug()<<zipcodes.at(i).performer;
        qDebug()<<zipcodes.at(i).status;
        qDebug()<<zipcodes.at(i).date_time;
        qDebug()<<zipcodes.at(i).qrpath;
        qDebug()<<"------------";
    }*/
    reset();
}

bool TableModel::rowsIsHave() const{

    return zipcodes.isEmpty() ? true : false;
}

QList<int> TableModel::listRows() const{

    QList<int> rows;
    for(int i = 0; i < zipcodes.size(); ++i){
        rows.append(zipcodes.at(i).id);
    }
    qSort(rows);

    return rows;
}

QStringList TableModel::listRowsPath() const{

    QStringList rows;
    for(int i = 0; i < zipcodes.size(); ++i){
        rows.append(zipcodes.at(i).qrpath);
    }

    return rows;
}

void TableModel::test(){
    for(int i = 0; i < zipcodes.size(); ++i) {
        qDebug()<<zipcodes.at(i).id;
        qDebug()<<zipcodes.at(i).performer;
        qDebug()<<zipcodes.at(i).status;
        qDebug()<<zipcodes.at(i).date_time;
        qDebug()<<zipcodes.at(i).qrpath;
        qDebug()<<"------------";
    }
}

/*
void TableModel::save(const QString &filename)
{
    if (!filename.isEmpty())
        m_filename = filename;
}*/
